<?php

/**
 * 
 * @author quang@mana.vn
 * 
 */

/**
 * sfWidgetFormDoctrineChoice represents a choice widget for a model.
 *
 * @package    symfony
 * @subpackage doctrine
 * @author     Fabien Potencier <fabien.potencier@symfony-project.com>
 * @author     Jonathan H. Wage <jonwage@gmail.com>
 * @version    SVN: $Id: sfWidgetFormDoctrineChoice.class.php 29679 2010-05-30 14:46:03Z Kris.Wallsmith $
 */
class sfWidgetFormPopupChoice extends sfWidgetForm
{
  /**
   * @see sfWidget
   */
  public function __construct($options = array(), $attributes = array()) {
    parent::__construct($options, $attributes);
  }

  /**
   * Constructor.
   *
   * Available options:
   *
   *  * model:        The model class (required)
   *  * method:       The method to use to display object values (__toString by default)
   *  * uri:
   *
   * @see sfWidgetFormSelect
   */
  protected function configure($options = array(), $attributes = array())
  {
    $this->addRequiredOption('model');
    $this->addRequiredOption('uri');
    $this->addOption('method', '__toString');

    parent::configure($options, $attributes);
  }
  
  public function getValue($val) {
    $query = Doctrine_Core::getTable($this->getOption('model'));
    $object = $query->find(array($val));

    $method = $this->getOption('method');
    if ($object)
    	return $object->$method();
    else
    	return '';
  }
  
  /**
   * Renders a HTML tag.
   *
   * The id attribute is added automatically to the array of attributes if none is specified.
   * If uses for "id_format" option to generate the id.
   *
   * @param  string $tag        The tag name
   * @param  array  $attributes An array of HTML attributes to be merged with the default HTML attributes
   *
   * @return string An HTML tag string
   */
  public function render($name, $value = null, $attributes = array(), $errors = array()) {
  	sfContext::getInstance()->getConfiguration()->loadHelpers('jQuery');
  	sfContext::getInstance()->getResponse()->addJavascript('jquery.colorbox-min.js');
  	sfContext::getInstance()->getResponse()->addStylesheet('colorbox.css');
  	
  	$attributes['name'] = $name;
  	$attributes['value'] = $value;
  	$attributes['type'] = 'hidden';
  	
  	$attributes = $this->fixFormId($attributes);
  	$id = $attributes['id'];
  	$value_id = $attributes['id'].'_value';
  	
  	$script = "
  		$(this).colorbox({
  			onLoad:function(){
	  			$.colorbox.onSelect = function(id, value) {
	  				$('#$id').val(id);
	  				$('#$value_id').html(value);
	  			}
  			}
 			});
 			return false;";
  	
  	return $this->renderTag('input', $attributes) .
  		"<span id='$value_id'>".$this->getValue($value)."</span>&nbsp;&nbsp;" .
  		link_to(image_tag('browse.gif'), $this->getOption('uri'), array('onclick'=>$script));
  }
}
